﻿using Dapper;
using MediatR;
using MySql.Data.MySqlClient;
using SCM.API.Read.Application.Command.Ledger;
using SCM.ErrorCode;
using SCM.Extensions.Ledger;
using SCM.Infrastructure.Interface;
using System.Text;

namespace SCM.API.Read.Application.Handler.Ledger
{
    public class GetguaranteeHandler : IRequestHandler<GetguaranteeCommand, APIPaging<GuaranteeDTO>>
    {
        IDatabaseContext db;

        public GetguaranteeHandler(IDatabaseContext db)
        {
            this.db = db;
        }

        public async Task<APIPaging<GuaranteeDTO>> Handle(GetguaranteeCommand request, CancellationToken cancellationToken)
        {
            var result = new APIPaging<GuaranteeDTO>();

            var countSql = new StringBuilder();
            var sqlBuilder = new StringBuilder();

            sqlBuilder.Append(@"SELECT 
                                        a.id,
                                        f.ProductId,
                                        f.ProductCode,
                                        f.ProductName,
                                        a.ProductStatus,
                                        b.CategoryId,
                                        b.CategoryName,
                                        f.Specifications,
                                        c.UnitId,
                                        c.UnitName,
                                        a.Barcode,
                                        d.DepotId,
                                        d.DepotName,
                                        e.LocationId,
                                        e.LocationName,
                                        a.Batch,
                                        a.StartTime,
                                        a.EndTime,
                                        a.isDel
                                FROM GuaranteeModel a join  CategoryModel   b on a.CategoryId=b.CategoryId 
                                                  join  UnitModel       c on a.UnitId=c.UnitId
                                                  join  DepotModel      d on a.DepotId=d.DepotId
                                                  join  LocationModel   e on a.LocationId=e.LocationId
                                                  join ProductModel f on a.ProductId=f.ProductId   
                                    WHERE a.IsDel=0 and b.IsDel=0 and c.IsDel=0 and d.IsDel=0 and e.IsDel=0 and f.IsDel=0   ");

            countSql.Append(@"SELECT COUNT(a.id)  FROM GuaranteeModel a join  CategoryModel   b on a.CategoryId=b.CategoryId 
                                                  join  UnitModel       c on a.UnitId=c.UnitId
                                                  join  DepotModel      d on a.DepotId=d.DepotId
                                                  join  LocationModel   e on a.LocationId=e.LocationId
                                                  join ProductModel f on a.ProductId=f.ProductId
                                    WHERE a.IsDel=0 and b.IsDel=0 and c.IsDel=0 and d.IsDel=0 and e.IsDel=0 and f.IsDel=0   ");

            var parameters = new DynamicParameters();
            if (!string.IsNullOrEmpty(request.Batch))
            {
                sqlBuilder.Append(" AND Batch LIKE @Batch ");
                parameters.Add("Batch", $"%{request.Batch}%");
                countSql.Append(" AND Batch LIKE @Batch ");
            }
            if (request.StartTime != null)
            {
                DateTime dateOnly = request.StartTime.Value.Date;
                sqlBuilder.Append(" AND CAST(a.StartTime AS DATE) = @DateOnly ");
                parameters.Add("@DateOnly", dateOnly);
                countSql.Append(" AND CAST(a.StartTime AS DATE) = @DateOnly ");
            }
            if (request.EndTime != null)
            {
                DateTime dateOnly = request.EndTime.Value.Date;
                sqlBuilder.Append(" AND CAST(a.EndTime AS DATE) = @DateOnly ");
                parameters.Add("@DateOnly", dateOnly);
                countSql.Append(" AND CAST(a.EndTime AS DATE) = @DateOnly ");
            }


            sqlBuilder.Append("ORDER BY id DESC ");
            sqlBuilder.Append("LIMIT @PageSize OFFSET @Offset ");
            parameters.Add("PageSize", request.PageSize);
            parameters.Add("Offset", (request.PageIndex - 1) * request.PageSize);

            

            var data = await db.DapperConnection.QueryAsync<GuaranteeDTO>(sqlBuilder.ToString(), parameters);
            var total = await db.DapperConnection.ExecuteScalarAsync<int>(countSql.ToString(), parameters);

            result.Msg = "显示成功";
            result.Code = APIEnum.Success;
            result.items = data.ToList();
            result.totalCount = total;
            result.totalPage = (int)Math.Ceiling((double)total / request.PageSize);
            return result;
        }
    }
}
